<?php
/**
 * V7
 * 
 * @author Leon
 *
 */
class data_event extends data {
	public function __construct($flag='', $param='', $level='low') {
		parent::__construct();
		if ($flag) {
			$this->add($flag, $param, $level);
		}
	}
	public function add ($flag, $param='', $level='low') {
		$level = ($level === 'high') ? 'high' : 'low';
		switch ($flag) {
			case 'update_friends':
				// array ('user_id' => int)
				break;
			case 'save_article':
				// array ('type' => 'outsite/insite_save/insite_share', 'user_id' => int, 'article_id' => int, 'url_id' => int, 'unchecked_friend_ids' => string, 'checked_circle_ids' => string)
				break;
			case 'create_circle':
				// array ('user_id'	=> int, 'circle_id' => int)
				break;
			case 'join_circle':
				// array ('user_id'	=> int, 'circle_id' => int)
				break;
			case 'follow_circle':
				// array ('user_id'	=> int, 'circle_id' => int)
				break;
			case 'friend_add':
				// array ( 'user_id'	=> $uid, 'friend_id'	=> $friend_id, )
				break;
			case 'merge_user':
				// array ( 'user_id'	=> , 'del_uid'=> )
				break;
			
			default:
				return false;
		}
		
		$insert_id = $this->db->execute("
				insert into
					event
				set
					flag	= '".$flag."',
					param 	= '".serialize($param)."',
					level	= '".$level."',
					status	= 0,
					dt_add	= '".date('Y-m-d H:i:s')."',
					dt_run	= '0000-00-00 00:00:00'
			");
		
		if ($insert_id) {
			if ($level === 'high') {
				// call web service to run it now ## to do ... ############################################################################
				$this->call_cron_now($insert_id);
				return $insert_id;
			} else {
				return $insert_id;
			}
		} else return false;
	}
	private function call_cron_now ($id) {
		$id = intval($id);
		if ($id) {
			$fp = fsockopen("uread.me", 80, $errno, $errstr, 3);
			if (!$fp) {
				$error_param = array (
					'id'		=> $id,
					'fp'		=> $fp,
					'errno'	=> $errno,
					'errstr'	=> $errstr
				);
				new data_error_devel('运行Event时，fsockopen 失败', $error_param, __CLASS__, __FUNCTION__, __LINE__);
				return false;
				echo "$errstr ($errno)<br />\n";
			} else {
				$out = "GET /auto.php HTTP/1.1\r\n";
				$out .= "Host: uread.me\r\n";
				$out .= "Connection: Close\r\n\r\n";
				fwrite($fp, $out);
				fclose($fp);
				return true;
			}
			
//			$ch = curl_init();
//			curl_setopt ($ch, CURLOPT_URL, 'http://www.uread.me/auto.php');
//			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 30);
//			curl_setopt ($ch, CURLOPT_POST, TRUE);
//			curl_setopt ($ch, CURLOPT_POSTFIELDS, 'id='.$id);
//			$return = curl_exec($ch);
//			curl_close($ch);
//			return $return;
		} else return false;
	}
	public function run_now ($id) {
		$id = intval($id);
		if ($id) {
			$execute = $this->db->execute('
				select
					*
				from
					event
				where
					id = "'.$id.'"	and
					status = 0
			');
			if ($execute[0]) {
				return $this->run($execute[0]);
			} else return false;
		} else return false;
	}
	public function run_all ($limit = 0) {
		$this->run_del_article();
		
		$limit = intval($limit);
		$execute = $this->db->execute('
			select
				*
			from
				event
			where
				status = 0
			'.(($limit) ? ' limit '.$limit : '').'
		');
		if (is_array($execute)) {
			foreach ($execute as $v) {
				$this->run($v);
			}
		}
	}
	private function run ($v) {
		$param = unserialize($v['param']);
		$function_name = 'run_'.$v['flag'];
		
		if (method_exists($this, $function_name)) {
			$return = $this->$function_name($param);
			if ($return) {
				$this->update_event_status($v['id'], 1);
				return true;
			} else {
				$this->update_event_status($v['id'], -1);
				return false;
			} 
		} else {
			$this->update_event_status($v['id'], -2);
			return false;
		} 
	}
	private function update_event_status ($id, $status) {
		return $this->db->execute('
			update
				`event`
			set
				`status`	= "'.$status.'",
				dt_run		= "'.date('Y-m-d H:i:s').'"
			where
				id			= "'.$id.'"
		');
	}
	private function run_update_friends ($param) {
		$data_user = new data_user();
		return $data_user->update_friends_by_event($param['user_id']);
	}
	/**
	 * 处理顺序：
	 *		发布到recommend article，
	 *		发布feed，
	 *		增加我在圈子中发布的文章数，
	 *		增加circle统计数，
	 *		增加url计数，
	 *		发布社交网站信息
	 * @param array $param array ('type' => 'outsite/insite_save/insite_share', 'user_id' => int, 'article_id' => int, 'url_id' => int, 'unchecked_friend_ids' => string, 'checked_circle_ids' => string)
	 */
	private function run_save_article ($param) {
		$param['type']				= ($param['type'] === 'outsite' or $param['type'] === 'insite_save' or $param['type'] === 'insite_share') ? $param['type'] : false;
		$param['user_id']				= intval($param['user_id']);
		$param['article_id']			= intval($param['article_id']);
		$param['url_id']				= intval($param['url_id']);
		$param['unchecked_friend_ids']	= format_id_string($param['unchecked_friend_ids'], FALSE);
		$param['checked_circle_ids']		= format_id_string($param['checked_circle_ids'], FALSE);
		
		if ($param['type'] and $param['user_id'] and $param['article_id']) {
			// 发布到recommend
			if ($param['unchecked_friend_ids']) {
				$data_recommend_article = new data_recommend_article();
				// 返回检查后的好友：核实好友，排除掉已经发送过的（避免重复发送）
				$checked_friends = $data_recommend_article->add_by_event_on_save_article($param['user_id'], $param['article_id'], $param['url_id'], $param['unchecked_friend_ids']);
			}
			// 发布feed，当circle是public时，当站外存档或者站内存档的时候
			if ($param['type'] == 'outsite' or $param['type'] == 'insite_save') {
				$data_feed = new data_feed();
				$data_feed->add_by_event_on_save_article($param['article_id']);
			}
			// 增加circle member中我的存档总数
			$data_circle = new data_circle();
			$data_circle->count_article_for_me($param['user_id'], $param['checked_circle_ids'], 1);
			// 增加circle统计数
			$data_circle->count_article($param['checked_circle_ids'], 1);
			// 增加url计数
			if ($param['url_id']) {
				$data_article = new data_article();
				$data_article->event_url_increase($param['url_id']);
			}
			// 剪切文章，生成摘要和下载大图到本地，替换文章中的图片链接到本地，摘出题图
			$data_save_article = new data_save_article();
			$data_save_article->auto_clip_by_event($param['article_id']);
			// 只要recommend时候，发布社交网络信息，如果私密文章则不发布。注：放在剪切文章之后，因为在人人网上发布的时候需要用到剪切后的摘要summary
			if ($checked_friends) {
				$data_user = new data_user();
				$data_user->publish_social_msg_by_event_on_save_article($param['user_id'], $param['article_id'], $checked_friends);
			}
			return true;
		} else return false;
	}
	private function run_del_article () {
		$execute = $this->db->execute('
			select
				id
			from
				save_article_del
			where
				status = 0
		');
		if (is_array($execute)) {
			foreach ($execute as $v) {
				$ids .= $v['id'].',';
			}
			$ids = substr($ids, 0, -1);
			
			$data_save_article = new data_save_article();
			if ($data_save_article->event_del($ids)) {
				$this->db->execute('
					update
						save_article_del
					set
						status = 1,
						dt_run = "'.date('Y-m-d H:i:s').'"
					where
						id	IN ('.$ids.')
				');
			} else return false;
		}
	}
	/**
	 * 创建circle
	 * 		发布feed
	 *
	 * @param array $param
	 * @return int
	 */
	private function run_create_circle ($param) {
		$data_feed = new data_feed();
		return $data_feed->event_add_by_circle_action($param['user_id'], $param['circle_id'], 'create_circle');
	}
	/**
	 * 加入圈子
	 * 		发布feed
	 * @param array $param
	 * @return int
	 */
	private function run_join_circle ($param) {
		$data_feed = new data_feed();
		return $data_feed->event_add_by_circle_action($param['user_id'], $param['circle_id'], 'join_circle');
	}
	/**
	 * follow circle
	 * 		发布feed
	 *
	 * @param array $param
	 * @return int
	 */
	private function run_follow_circle ($param) {
		$data_feed = new data_feed();
		return $data_feed->event_add_by_circle_action($param['user_id'], $param['circle_id'], 'follow_circle');
	}
	/**
	 * 两个好友，互相复制feed
	 *
	 * @param array $param
	 * array ( 	'user_id'	=> $uid,
	 * 			'friend_id'	=> $friend_id,
	 * 		);
	 * @return bool
	 */
	private function run_friend_add ($param) {
		$param['user_id']		= intval($param['user_id']);
		$param['friend_id']	= intval($param['friend_id']);
		
		if ($param['user_id'] and $param['friend_id']) {
			// 互相复制feed
			$data_feed = new data_feed();
			$data_feed->event_copy_feed($param['user_id'], $param['friend_id']);
			return true;
		} else return false;
	}
	
	private function run_merge_user ($param) {
		$data_user = new data_user();
		return $data_user->merge_user_by_event($param['user_id'], $param['del_uid']);
	}
}
?>